<?php

class DB {
	
	private static function fileUrl($id) {
		global $DATA_PATH;
		return $_SERVER['DOCUMENT_ROOT'].$DATA_PATH."/$id.dat";
	}

	public static function load($id) {
		$f = DB::fileUrl($id);
		if(file_exists($f)) {
			return unserialize(file_get_contents($f));
		}
		return false;
	}

	public static function save($obj) {
		if(isset($obj->id) && $obj->id !== false){
			$id = $obj->id;
		} else {
			$id = DB::nextId();
			$obj->id = $id;
		}
		$myFile = DB::fileUrl($id);
		$fh = fopen($myFile, 'w') or die("can't open file");
		fwrite($fh, serialize($obj));
		fclose($fh);
		return $id;
	}

	private static function nextId() {
		do {
			$id = rand(1,10000000);
		} while(file_exists(DB::fileUrl($id)));
		return $id;
	}
	
	/**
	** Allow to contact only registered servers
	** Return true if server is OK
	**/
	public static function checkServer() {
		if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']=="127.0.0.1") {
			// OK
			return true;
		}
		return false;
	}

}

?>